import Vue from "vue";
import VueRouter from "vue-router";
import store from '@/store/index'

Vue.use(VueRouter);

// 重写push，防止跳转同一路由报错
const routerPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch((error) => error);
};

const routes = [
  {
    path: "/",
    redirect: "/home",
    component: () => import("../views/platform/index.vue"),
    children: [
      {
        path: "/home",
        name: "home",
        component: () => import("../views/HomePage/index.vue"),
      },
      {
        path: "/service",
        name: "service",
        component: () => import("../views/service/index.vue"),
      },
      {
        path: "/proxy",
        name: "proxy",
        component: () => import("../views/proxy/index.vue"),
      },
      {
        path: '/order/list',
        name: "orderList",
        component: () => import("../views/orderList/index.vue"),
      },
      {
        path: '/order/analysis',
        name: "orderAnalysis",
        component: () => import("../views/orderAnalysis/index.vue"),
      },
      {
        path: '/code',
        name: "code",
        component: () => import("../views/code/index.vue"),
      },
      {
        path: '/merchant',
        name: "merchant",
        component: () => import("../views/merchant/index.vue"),
      },
      {
        path: '/channel',
        name: "channel",
        component: () => import("../views/channel/index.vue"),
      },
      {
        path: '/account',
        name: "account",
        component: () => import("../views/account/index.vue"),
      },
      {
        path: "/demo",
        name: "demo",
        component: () => import("../views/demo/index.vue"),
        children: [
          {
            path: "table",
            name: "table",
            component: () => import("../views/demo/table/index.vue"),
          },
          {
            path: "icon",
            name: "icon",
            component: () => import("../views/demo/icon/index.vue"),
          },
          {
            path: "getFormItem",
            name: "getFormItem",
            component: () => import("../views/demo/formitem/index.vue"),
          },
          {
            path: "searchForm",
            name: "searchForm",
            component: () => import("../views/demo/search/index.vue"),
          },
        ],
      },
    ]
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/Login/index.vue"),
  },
];

const router = new VueRouter({
  // mode: 'history',
  routes,
});

// 设置全局前置守卫
router.beforeEach((to, from, next) => {
  const { user: { isLogin } } = store.state;
  if (to.path !== '/login') {
    if (!isLogin) {
      next('/login');
    } else {
      next();
    }
  } else {
    next();
  }
})

export default router;
